package com.eascs.web.p2p.action;

import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.app.dao.PageResult;
import com.eascs.common.util.StringUtil;
import com.eascs.p2p.common.entity.AdminUserEntity;
import com.eascs.p2p.common.entity.InvestObjExtEntity;
import com.eascs.p2p.common.entity.InvestObjectEntity;
import com.eascs.p2p.common.service.IFileService;
import com.eascs.p2p.common.service.IInvestObjectService;
import com.eascs.p2p.common.service.IInvestorRecordService;
import com.eascs.p2p.common.service.InvestorService;
import com.eascs.p2p.common.vo.BidVO;
import com.eascs.p2p.common.vo.InvestRecordVO;
import com.eascs.p2p.common.vo.ModelResult;
import com.eascs.p2p.common.wallet.service.InvestorWalletService;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;

@RestController
@RequestMapping("/bidRest")
public class BidRestController extends BaseRestController {

	@Reference
	IInvestObjectService investObjectService;
	@Reference
	IFileService iFileService;
	@Reference
	InvestorWalletService investorWalletService;
	@Reference
	IInvestorRecordService investorRecordService;
	@Reference
	InvestorService investorService;

	/**
	 * @Title: saveBid
	 * @Description: 保存标的信息
	 * @author lwx
	 * @param BidVO
	 * @return
	 * @return BaseRestResult<String>
	 * @throws @date
	 *             2016年7月4日 下午4:32:08
	 */

	@RequestMapping(value = "/save_bid")
	public BaseRestResult<String> saveBid(BidVO vo,HttpServletRequest request) {
		HttpSession session =request.getSession();
		AdminUserEntity userName=(AdminUserEntity) session.getAttribute("adminUser");
		String operator=userName!=null?userName.getId():"";
		if (("edit").equals(vo.getOpType())) {
			ModelResult<InvestObjectEntity> v_model = investObjectService.findInvestObjectDetail(vo.getId());
			InvestObjectEntity investObjectEntityupdate = v_model.getModel();
			setEntity(vo, investObjectEntityupdate);
			investObjectEntityupdate.setRegenerator(operator);
			InvestObjExtEntity ext = new InvestObjExtEntity();
			ext.setContent(vo.getContent());
			ModelResult<Boolean> model = investObjectService.updateInvestObjectEntity(investObjectEntityupdate, ext);
			if (model.isSuccess()) {
				if (model.getModel()) {
					// 修改附件信息
					// iFileService.updateFile(new
					// String[]{vo.getContract(),vo.getCard()}, vo.getId());
					// BaseRestResult.info("修改成功").andRedirect("/bid/index");
					return BaseRestResult.info("修改成功");
				} else {
					return BaseRestResult.info("数据库操作失败");
				}
			} else {
				return BaseRestResult.info("修改失败");
			}
		} else {
			InvestObjectEntity investObjectEntity = new InvestObjectEntity();
			setEntity(vo, investObjectEntity);
			investObjectEntity.setCreator(operator);
			investObjectEntity.setRegenerator(operator);
			investObjectEntity.setObjectStatus(1);
			InvestObjExtEntity ext = new InvestObjExtEntity();
			ext.setContent(vo.getContent());
			ModelResult<String> model = investObjectService.addInvestObjectEntity(investObjectEntity, ext);
			if (model.isSuccess()) {
				if (StringUtil.isNotBlank(model.getModel())) {
					ModelResult<InvestObjectEntity> v_model = investObjectService
							.findInvestObjectDetail(model.getModel());
					/*
					 * //新增还款计划 if(v_model.getModel()!=null){
					 * investObjectService.addRefundPlan(v_model.getModel()); }
					 */
					// 修改附件信息
					// iFileService.updateFile(new
					// String[]{vo.getContract(),vo.getCard()}, vo.getId());
					return BaseRestResult.info("添加成功")
							.andRedirect("/bid/op_bid?opType=edit&id=" + v_model.getModel().getId());
				} else {
					return BaseRestResult.info("数据库操作失败");
				}
			} else {
				return BaseRestResult.info("添加失败");
			}
		}

	}

	private void setEntity(BidVO vo, InvestObjectEntity investObjectEntity) {
		investObjectEntity.setGroupTeam(vo.getGroupTeam());
		investObjectEntity.setTitle(vo.getTitle());
		investObjectEntity.setLoaneeId(vo.getLoaneeId());
		investObjectEntity.setLoaneeName(vo.getLoaneeName());
		investObjectEntity.setAnnualizedYield(vo.getAnnualizedYield());
		investObjectEntity.setLoanAmount(vo.getLoanAmount());
		investObjectEntity.setLowestInvestentAmount(vo.getLowestInvestentAmount());
		// investObjectEntity.setServiceFeeRate(vo.getServiceFeeRate());
		investObjectEntity.setDeadline(vo.getDeadline());
		investObjectEntity.setDeadlineType(vo.getDeadlineType());
		investObjectEntity.setRefundType(vo.getRefundType());
		investObjectEntity.setObjectIntro(vo.getObjectIntro());
		investObjectEntity.setBillCode(vo.getBillCode());
		SimpleDateFormat d = new SimpleDateFormat("yyyy-MM-dd");
		if (StringUtil.isNotBlank(vo.getOnlineTime())) {
			try {
				investObjectEntity.setOnlineTime(d.parse(vo.getOnlineTime()));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (StringUtil.isNotBlank(vo.getFailureTime())) {
			try {
				investObjectEntity.setFailureTime(d.parse(vo.getFailureTime()));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @Title: verifyBid
	 * @Description: 标的信息审核/发布
	 * @author 张庆奇
	 * @param id
	 *            标的id,status 操作
	 * @return
	 * @return BaseRestResult<String>
	 * @throws @date
	 *             2016年7月4日 下午4:32:08
	 */
	@RequestMapping(value = "/verifyBid")
	public BaseRestResult<String> verifyBid(String op, String id,HttpServletRequest request) {
		String url = "/bid/index";
		BaseRestResult<String> result = null;
		InvestObjectEntity investObject = null;
		int status = 1;
		ModelResult<InvestObjectEntity> model = investObjectService.findInvestObjectDetail(id);
		if (model.isSuccess()) {
			investObject = model.getModel();
		}
		if (investObject.getObjectStatus() == 2 && ("aduit").equals(op)) {
			return result = BaseRestResult.warn("已经审核完毕，不需要重新审核");
		}

		if (investObject.getObjectStatus() == 3 && ("publish").equals(op)) {
			return result = BaseRestResult.warn("已经发布完毕，不需要重新发布");
		}
		if ("publish".equals(op)) {
			status = 3;
		} else if ("aduit".equals(op)) {
			status = 2;
		} else if ("over".equals(op)) {
			status = 10;
			url = "/bid/directInsurance";
			// 标的终止后钱包流水处理(无标的状态修改)
			ModelResult<Boolean> modelFlag = investorWalletService.stopInvestWalletFlow(id);
			if (!modelFlag.isSuccess() || !modelFlag.getModel()) {
				return result = BaseRestResult.warn("标的终止：标的终止后钱包流水处理失败");
			}
		}
		HttpSession session =request.getSession();
		AdminUserEntity userName=(AdminUserEntity) session.getAttribute("adminUser");
		String operator=userName!=null?userName.getId():"";
		ModelResult<Boolean> flag_model = investObjectService.verifyBid(id, status,operator);
		boolean flag = false;
		if (flag_model.isSuccess()) {
			flag = flag_model.getModel();
		}

		if (flag) {
			result = BaseRestResult.warn("操作成功").andRedirect(url);
		} else {
			result = BaseRestResult.error("操作失败");
		}

		return result;

	}

	/**
	 * @Title: loanMoney
	 * @Description: 放款接口
	 * @author 张庆奇
	 * @param id
	 * @return
	 * @return BaseRestResult<String>
	 * @throws @date
	 *             2016年8月8日 下午5:05:02
	 */
	@RequestMapping(value = "/loanMoney")
	public BaseRestResult<String> loanMoney(String id,HttpServletRequest request) {
		HttpSession session =request.getSession();
		AdminUserEntity userName=(AdminUserEntity) session.getAttribute("adminUser");
		String operator=userName!=null?userName.getId():"";
		String url = "/bid/directInsurance";
		BaseRestResult<String> result = null;
		InvestObjectEntity investObject = null;
		ModelResult<InvestObjectEntity> model = investObjectService.findInvestObjectDetail(id);
		if (model.isSuccess()) {
			investObject = model.getModel();
		}

		// 1.to-do 调用放款接口

		boolean flag = true;//因为现在还没有放款借款，暂时还需要生产还款计划、客户投资明细所以，flag设定为true
		if (flag) {
			// 如果成功，则调用还款计划列表
			
			if (investObject != null) {
				investObjectService.verifyBid(id, 5,operator);
				investObjectService.addRefundPlan(investObject);// 生成还款计划
				investObjectService.addInvestorIncomeDetail(id);//生成用户投资明细
			}
			result = BaseRestResult.warn("放款成功").andRedirect(url);
		} else {
			result = BaseRestResult.error("放款失败");
		}

		return result;

	}
	
	/**
	 * @Title: record
	 * @Description: 
	 * @author 张庆奇
	 * @param vo
	 * @return
	 * @return HtmlRestResult
	 * @throws
	 * @date 2016年8月3日 下午3:11:02
	 */
	@RequestMapping(value = "/record")
	public HtmlRestResult record(InvestRecordVO vo) {

		vo.setPageSize(10);
		ModelResult<PageResult<Object[]>> model =investorRecordService.findPageInvestRecordEntity(vo);
		PageResult<Object[]> pageResult=new PageResult<Object[]>();
		if(model.isSuccess()){
			 pageResult = model.getModel();
		} 
			
		

		String[] titles = { "投资项目", "投资日期", "投资金额", "利息金额", "投资人" ,"投资人手机号"};
		
		
		
		String findCondition = "";
		String pageUrl = "/bidRest/record";

		if (vo != null) {
			String title=vo.getTitle() == null ? "" : vo.getTitle();
			String name = vo.getName() == null ? "" : vo.getName();
			String mobile = vo.getMobile() == null ? "" : vo.getMobile();
			String beginCreateTime = vo.getBeginCreateTime() == null ? "" : vo.getBeginCreateTime();
			String endCreateTime = vo.getEndCreateTime() == null ? "" : vo.getEndCreateTime();

			findCondition = "?name=" + name +"&mobile=" + mobile+"&beginCreateTime=" + beginCreateTime +"&endCreateTime=" + endCreateTime+"&title=" + title  ;

			pageUrl = pageUrl + findCondition;
		}
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles, pageUrl + "&showPage=");
		paginationInfo.setBuildPagingNavigation(true);
		paginationInfo.setFirstRenderColumnIndex(0);
		ViewContext.put("paginationInfo", paginationInfo);
		ViewContext.put("vo", vo);
		ModelResult<InvestRecordVO> recordModel=investorRecordService.findInvestRecordVO(vo);
		InvestRecordVO  investRecord=new InvestRecordVO();
		if(recordModel.isSuccess()){
			investRecord=recordModel.getModel();
			ViewContext.put("investRecord", investRecord);
		}
		
		ModelResult<Integer> investorNumModel=investorRecordService.getInvestorNum(vo);
		int investorNum=0;
		if(investorNumModel.isSuccess()){
			investorNum=investorNumModel.getModel();
			ViewContext.put("investorNum", investorNum);
		}
		BaseRestResult.refresh();
		
		return HtmlRestResult.popHtmlFragment("/bid/record");
	
	}



}
